<script setup lang="ts" name="DraggableContainer">
import { shallowRef } from 'vue'
import { buildUUID } from '@/utils/uuid'
import draggable from 'vuedraggable'
import { cloneDeep } from 'lodash-es'
import useDraggableAction from '../../hooks/useDraggableAction'

const emit = defineEmits(['widgetChange'])
const props = defineProps({
  pageConfig: { type: Object },
  contentHeight: { type: Number }
})
const pageOptions = toRef(props, 'pageConfig')
const { widgetModules, defaultConfig } = useDraggableAction()
const groupFurnish = ref({
  name: 'widgetDrag',
  pull: false,
  put: true
})
const furnishList = ref([])

const widgetPageDragEndHandler = (e) => {
  console.log(furnishList.value, '布局组件数据')
  console.log(e, '布局组件')
  const newItem = cloneDeep(furnishList.value[e.newIndex])
    console.log(newItem)
    if (e.pullMode && e.pullMode === 'clone') {
      furnishList.value.forEach((item, index) => {
        if (index !== e.newIndex) {
          item.active = false
        }
      })
      newItem.uuid = newItem.module + '_' + buildUUID()
      console.log(widgetModules.value)
      console.log(pageOptions.value)
      newItem.component = shallowRef(widgetModules.value[`../components/widget/${newItem.module}/${newItem.package}/${pageOptions.value.device}/source/index.vue`].default)
      newItem.active = true
      newItem.config = cloneDeep(defaultConfig.value[`../components/widget/${newItem.module}/${newItem.package}/${pageOptions.value.device}/index.ts`].defaultConfig)
      furnishList.value.splice(e.newIndex, 1, newItem)
      emit('widgetChange', newItem)
    }
}
const clearFurnish = () => {
  furnishList.value = []
}

const copyWidget = (e) => {
  const index = furnishList.value.findIndex((item) => {
    return item.uuid === e.uuid
  })
  const newItem = cloneDeep(e)
  newItem.uuid = newItem.module + '_' + buildUUID()
  newItem.component = shallowRef(widgetModules.value[`./components/widget/${newItem.module}/${newItem.package}/${pageOptions.value.device}/source/index.vue`].default)
  newItem.active = true
  furnishList.value.forEach((item) => {
    item.active = false
  })
  furnishList.value.splice(index + 1, 0, newItem)
  emit('widgetChange', newItem)
  console.log(furnishList.value)
}

const deleteWidget = (e) => {
  const index = furnishList.value.findIndex((item) => {
    return item.uuid === e.uuid
  })
  furnishList.value.splice(index, 1)
  let activeIndex = 0
  if (index === furnishList.value.length) {
    activeIndex = index - 1
  } else {
    activeIndex = index
  }
  furnishList.value.forEach((item, idx) => {
    if (activeIndex === idx) {
      item.active = true
    }
  })
}

// 拖拽开始的事件
const onSortStart = (e) => {
  console.log(e, '开始拖拽')
  console.log(furnishList.value)
}

// 拖拽结束的事件
const onSortEnd = (e) => {
  console.log(e, '结束拖拽')
  console.log(furnishList.value)
}

const onSortMove = (e, originalEvent) => {
  console.log(e, 'onMove')
  console.log(originalEvent, 'onMove')
}

const onSortItem = (e, originalEvent) => {
  console.log(e, '排序对象')
  console.log(originalEvent, '排序对象2')
}

// 获取当前选中的布局模块
const widgetElementClickHandle = (e) => {
  furnishList.value.forEach((item) => {
    item.active = false
    if (item.uuid === e.uuid) {
      item.active = true
      emit('widgetChange', item)
    }
  })
}

const propertyChangeHandler = (v) => {
  console.log(v)
  if (v.type === 'package') {
    furnishList.value.forEach((item) => {
      if (item.active) {
        item.package = v.value
        item.component = shallowRef(widgetModules.value[`../components/widget/${item.module}/${item.package}/${pageOptions.value.device}/source/index.vue`].default)
        item.config = cloneDeep(defaultConfig.value[`../components/widget/${item.module}/${item.package}/${pageOptions.value.device}/index.ts`].defaultConfig)
        emit('widgetChange', item)
      }
    })
  }
}
// 子组件将方法暴露给父组件
defineExpose({ clearFurnish, widgetPageDragEndHandler, propertyChangeHandler })
</script>

<template>
  <draggable
    class="widget-container"
    v-model="furnishList"
    :scroll="true"
    :group="groupFurnish"
    item-key="uuid"
    ghostClass="placeholder"
    animation="300"
    handle=".mover"
    :style="{ minHeight: contentHeight + 'px', background: pageOptions.pageSettings ? pageOptions.pageSettings.bgColor : '#ffffff' }"
    @start="onSortStart"
    @end="onSortEnd"
    :move="onSortMove"
    :onSort="onSortItem">
    <template #item="{ element }">
      <div :class="['widget-wrap', element.active ? 'is-active' : '']" @click="widgetElementClickHandle(element)">
        <div class="widget-view">
          <component v-if="element.component" :is="element.component" :key="element.uuid" :config="element.config"></component>
          <div class="empty" v-else></div>
        </div>
        <div class="widget-drag" v-if="element.active">
          <span class="item-button mover"><svg-icon icon="ri:drag-move-2-fill"></svg-icon></span>
        </div>
        <div class="widget-action" v-if="element.active">
          <span class="item-button" @click="copyWidget(element)" title="复制"><svg-icon icon="ri:checkbox-multiple-blank-line"></svg-icon></span>
          <span class="item-button" @click="deleteWidget(element)" title="删除"><svg-icon icon="ri:delete-bin-line"></svg-icon></span>
        </div>
      </div>
    </template>
  </draggable>
</template>

<style scoped lang="scss">
.widget-container {

  .chosen,
  .ghost {
    height: 4px;
    overflow: hidden;
    background: var(--el-color-danger);
    border-radius: 0 0 2px 2px;

    &::before {
      visibility: hidden;
    }

    * {
      visibility: hidden;
    }
  }

  .placeholder {
    overflow: hidden;
    background: var(--el-color-danger);
    border-radius: 0 0 2px 2px;

    &::before {
      visibility: hidden;
    }

    * {
      visibility: hidden;
    }
  }

  .widget-wrap {
    position: relative;

    &::before {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      display: block;
      width: 100%;
      height: 100%;
      border: 1px dashed var(--el-border-color-darker);
      content: '';
      pointer-events: none !important;
    }

    &:hover {
      &::before {
        border: 1px solid var(--el-color-primary);
      }
    }

    &.is-active {
      &::before {
        border: 3px solid var(--el-color-primary);
      }

      &:hover {
        &::before {
          border: 3px solid var(--el-color-primary);
        }
      }
    }

    .widget-drag,
    .widget-action {
      position: absolute;
      z-index: 10;
      font-size: 0;
      line-height: 0;

      .item-button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 20px;
        height: 20px;
        background-color: var(--el-color-primary);

        .el-icon {
          color: var(--el-color-white);
        }
      }
    }

    .widget-drag {
      top: 0;
      left: 0;

      .item-button {
        cursor: move;
      }
    }

    .widget-action {
      right: 0;
      bottom: 0;

      .item-button {
        margin-left: 1px;
        cursor: pointer;
      }
    }
  }

  .widget-view {
    position: relative;
    margin: 0;
    padding: 0;
  }
}
</style>
